<template>
  <div class="game-container">
    <!-- 顶部控制区 -->
    <div class="top-controls">
      <div class="difficulty">
        <span>难度:</span>
        <button @click="setDifficulty('easy')" :class="{ active: difficulty === 'easy' }">简单</button>
        <button @click="setDifficulty('medium')" :class="{ active: difficulty === 'medium' }">中等</button>
        <button @click="setDifficulty('hard')" :class="{ active: difficulty === 'hard' }">困难</button>
      </div>
      
      <div class="skin">
        <span>皮肤:</span>
        <button @click="toggleSkin">{{ currentSkinName }}</button>
      </div>
    </div>

    <!-- 游戏状态 -->
    <div class="status">
      得分: {{ score }} | 长度: {{ snake.length }} | 剩余生命: 
      <span v-for="i in lives" :key="i">❤️</span>
      <span v-if="lives <= 0">💀</span>
    </div>

    <!-- 游戏棋盘 -->
    <div class="game-board" :style="boardStyle">
      <!-- 蛇身 -->
      <div 
        v-for="(segment, index) in snake" 
        :key="index"
        class="snake-segment"
        :style="getSegmentStyle(segment, index)"
        :class="currentSkinClass"
      ></div>

      <!-- 食物 - 支持多种类型 -->
      <div 
        v-for="(food, index) in foods" 
        :key="index"
        class="food"
        :style="food.positionStyle"
        :class="food.typeClass"
        @click="eatFood(food)"
      >
        {{ food.icon }}
      </div>
    </div>

    <!-- 控制按钮 -->
    <div class="controls">
      <button @click="startGame">{{ gameRunning ? '暂停' : '新游戏' }}</button>
      
      <div class="direction-controls">
        <button @click="changeDirection('up')" class="arrow up"></button>
        <button @click="changeDirection('left')" class="arrow left"></button>
        <button @click="changeDirection('right')" class="arrow right"></button>
        <button @click="changeDirection('down')" class="arrow down"></button>
      </div>
    </div>

    <!-- 排行榜 -->
    <div class="leaderboard" v-if="showLeaderboard">
      <h3>排行榜</h3>
      <ul>
        <li v-for="(entry, index) in topScores" :key="index">
          {{ index + 1 }}. {{ entry.name }} - {{ entry.score }}
        </li>
      </ul>
      <button @click="showLeaderboard = false">关闭</button>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, onBeforeUnmount } from 'vue'

export default {
  setup() {
    // 游戏配置
    const gridSize = ref(20)
    const cellSize = 30 // 每个格子的像素大小
    
    // 难度配置
    const difficulties = {
      easy: 300,    // 简单难度 - 300ms移动一次
      medium: 200,  // 中等难度 - 200ms移动一次（默认）
      hard: 100     // 困难难度 - 100ms移动一次
    }
    
    // 皮肤配置
    const skinTypes = {
      classic: { name: '经典绿', color: '#0f0' },
      flame: { name: '火焰红', color: '#f00' },
      rainbow: { name: '彩虹渐变', color: 'rainbow' }
    }
    
    // 食物类型配置
    const foodTypes = [
      { type: 'normal', icon: '🍎', score: 10, color: '#4CAF50', effect: null },
      { type: 'speedUp', icon: '🚀', score: 20, color: '#FF4444', effect: 'speedUp' },
      { type: 'speedDown', icon: '🛑', score: 5, color: '#0088FF', effect: 'speedDown' },
      { type: 'life', icon: '❤️', score: 0, color: '#FF88AA', effect: 'addLife' }
    ]
    
    // 状态管理
    const snake = reactive([{ x: 5, y: 5 }])
    const foods = reactive([])
    const direction = ref('right')
    const score = ref(0)
    const lives = ref(3)
    const gameRunning = ref(false)
    const gameLoop = ref(null)
    const speedEffect = ref(null)
    const difficulty = ref('medium')
    const currentSkin = ref('classic')
    const showLeaderboard = ref(false)
    const scoreHistory = ref([])
    
    // 计算属性
    const boardStyle = computed(() => ({
      width: `${gridSize.value * cellSize}px`,
      height: `${gridSize.value * cellSize}px`,
      border: '2px solid #333',
      position: 'relative',
      margin: '20px auto',
      backgroundColor: '#000',
      borderRadius: '8px',
      boxShadow: '0 0 20px rgba(0,0,0,0.5)'
    }))
    
    const currentSpeed = computed(() => {
      if (speedEffect.value) {
        return speedEffect.value.speed
      }
      return difficulties[difficulty.value]
    })
    
    const currentSkinName = computed(() => {
      return skinTypes[currentSkin.value].name
    })
    
    const currentSkinClass = computed(() => {
      return `skin-${currentSkin.value}`
    })
    
    const topScores = computed(() => {
      return [...scoreHistory.value].sort((a, b) => b.score - a.score).slice(0, 10)
    })
    
    // 游戏方法
    const startGame = () => {
      // 清除现有游戏循环
      clearInterval(gameLoop.value)
      
      // 重置游戏状态
      snake.splice(0, snake.length, { x: 5, y: 5 })
      direction.value = 'right'
      score.value = 0
      lives.value = 3
      foods.splice(0, foods.length)
      speedEffect.value = null
      gameRunning.value = true
      
      // 生成初始食物
      spawnFood()
      
      // 启动游戏循环
      gameLoop.value = setInterval(move, currentSpeed.value)
    }
    
    const move = () => {
      const head = { ...snake[0] }
      
      // 根据当前方向移动蛇头
      switch(direction.value) {
        case 'up': head.y--; break
        case 'down': head.y++; break
        case 'left': head.x--; break
        case 'right': head.x++; break
      }
      
      // 检查碰撞
      if (checkCollision(head)) {
        lives.value--
        if (lives.value <= 0) {
          gameOver()
          return
        } else {
          // 重置蛇头位置
          snake.splice(0, snake.length, { x: 5, y: 5 })
          direction.value = 'right'
          return
        }
      }
      
      // 检查是否吃到食物
      let ateFood = false
      foods.forEach((food, index) => {
        if (head.x === food.x && head.y === food.y) {
          handleFoodEffect(food)
          foods.splice(index, 1)
          spawnFood()
          ateFood = true
        }
      })
      
      // 如果没吃到食物，移除尾部
      if (!ateFood) {
        snake.pop()
      }
      
      // 添加新头部
      snake.unshift(head)
    }
    
    const checkCollision = (pos) => {
      return (
        pos.x < 0 || 
        pos.x >= gridSize.value || 
        pos.y < 0 || 
        pos.y >= gridSize.value ||
        // 检查是否撞到自己（忽略头部）
        snake.slice(1).some(seg => seg.x === pos.x && seg.y === pos.y)
      )
    }
    
    const spawnFood = () => {
      // 随机选择食物类型
      const foodType = foodTypes[Math.floor(Math.random() * foodTypes.length)]
      
      // 生成随机位置
      let x, y
      do {
        x = Math.floor(Math.random() * gridSize.value)
        y = Math.floor(Math.random() * gridSize.value)
      } while (snake.some(seg => seg.x === x && seg.y === y))
      
      // 添加新食物
      foods.push({
        ...foodType,
        x,
        y,
        positionStyle: computed(() => ({
          left: `${x * cellSize}px`,
          top: `${y * cellSize}px`,
          transition: 'all 0.3s'
        })),
        typeClass: `food-${foodType.type}`
      })
    }
    
    const handleFoodEffect = (food) => {
      // 更新分数
      if (food.score) {
        score.value += food.score
      }
      
      // 处理特殊效果
      switch(food.effect) {
        case 'speedUp':
          applySpeedEffect(100, 2000) // 加速到100ms，持续2秒
          break
        case 'speedDown':
          applySpeedEffect(400, 2000) // 减速到400ms，持续2秒
          break
        case 'addLife':
          if (lives.value < 5) { // 最多5条命
            lives.value++
          }
          break
      }
    }
    
    const applySpeedEffect = (speed, duration) => {
      // 清除现有速度效果
      if (speedEffect.value) {
        clearTimeout(speedEffect.value.timer)
      }
      
      // 应用新的速度效果
      speedEffect.value = {
        speed,
        timer: setTimeout(() => {
          speedEffect.value = null
          // 重新设置游戏循环速度
          clearInterval(gameLoop.value)
          gameLoop.value = setInterval(move, currentSpeed.value)
        }, duration)
      }
      
      // 立即更新游戏循环速度
      clearInterval(gameLoop.value)
      gameLoop.value = setInterval(move, speed)
    }
    
    const gameOver = () => {
      gameRunning.value = false
      clearInterval(gameLoop.value)
      
      // 保存分数到排行榜
      const playerName = prompt('游戏结束！请输入你的名字:', '匿名玩家') || '匿名玩家'
      scoreHistory.value.push({
        name: playerName,
        score: score.value,
        date: new Date().toLocaleDateString()
      })
      
      // 保存到localStorage
      localStorage.setItem('snakeScores', JSON.stringify(scoreHistory.value))
      
      // 显示排行榜
      showLeaderboard.value = true
    }
    
    const loadScores = () => {
      const savedScores = localStorage.getItem('snakeScores')
      if (savedScores) {
        scoreHistory.value = JSON.parse(savedScores)
      }
    }
    
    const changeDirection = (newDir) => {
      // 防止180度转向（不能直接反向移动）
      const oppositeDirections = {
        up: 'down',
        down: 'up',
        left: 'right',
        right: 'left'
      }
      
      if (newDir !== oppositeDirections[direction.value]) {
        direction.value = newDir
      }
    }
    
    const setDifficulty = (newDifficulty) => {
      difficulty.value = newDifficulty
      if (gameRunning.value) {
        // 如果游戏正在运行，立即更新速度
        clearInterval(gameLoop.value)
        gameLoop.value = setInterval(move, currentSpeed.value)
      }
    }
    
    const toggleSkin = () => {
      const skinKeys = Object.keys(skinTypes)
      const currentIndex = skinKeys.indexOf(currentSkin.value)
      currentSkin.value = skinKeys[(currentIndex + 1) % skinKeys.length]
    }
    
    const getSegmentStyle = (segment, index) => {
      let color = ''
      
      if (currentSkin.value === 'classic') {
        color = '#0f0' // 经典绿色
      } else if (currentSkin.value === 'flame') {
        // 火焰渐变
        const hue = (index * 10) % 60
        color = `hsl(${hue}, 100%, 50%)`
      } else if (currentSkin.value === 'rainbow') {
        // 彩虹渐变
        const hue = (index * 36) % 360
        color = `hsl(${hue}, 100%, 60%)`
      }
      
      return {
        left: `${segment.x * cellSize}px`,
        top: `${segment.y * cellSize}px`,
        width: `${cellSize - 2}px`,
        height: `${cellSize - 2}px`,
        backgroundColor: color,
        position: 'absolute',
        borderRadius: '5px',
        transition: 'all 0.1s' // 平滑移动动画
      }
    }
    
    // 生命周期钩子
    onMounted(() => {
      // 加载历史分数
      loadScores()
      
      // 绑定键盘事件
      window.addEventListener('keydown', (e) => {
        const keyMap = {
          ArrowUp: 'up',
          ArrowDown: 'down',
          ArrowLeft: 'left',
          ArrowRight: 'right',
          ' ': gameRunning.value ? 'pause' : 'start' // 空格键控制暂停/开始
        }
        
        if (keyMap[e.key]) {
          e.preventDefault()
          
          if (keyMap[e.key] === 'pause') {
            gameRunning.value = false
            clearInterval(gameLoop.value)
          } else if (keyMap[e.key] === 'start') {
            if (!gameRunning.value) {
              startGame()
            }
          } else {
            changeDirection(keyMap[e.key])
          }
        }
      })
    })
    
    onBeforeUnmount(() => {
      clearInterval(gameLoop.value)
      if (speedEffect.value) {
        clearTimeout(speedEffect.value.timer)
      }
      window.removeEventListener('keydown', null)
    })
    
    // 暴露给模板
    return {
      snake,
      foods,
      score,
      lives,
      boardStyle,
      gameRunning,
      startGame,
      changeDirection,
      getSegmentStyle,
      difficulty,
      setDifficulty,
      currentSkin,
      currentSkinName,
      toggleSkin,
      showLeaderboard,
      topScores
    }
  }
}
</script>

<style scoped>
/* 游戏容器 */
.game-container {
  font-family: 'Arial', sans-serif;
  text-align: center;
  background: linear-gradient(135deg, #2c3e50, #3498db);
  min-height: 100vh;
  padding: 20px;
  color: white;
}

/* 顶部控制区 */
.top-controls {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  padding: 10px;
  background: rgba(0,0,0,0.3);
  border-radius: 8px;
}

.top-controls button {
  padding: 8px 15px;
  margin: 0 5px;
  border: none;
  border-radius: 4px;
  background: rgba(255,255,255,0.2);
  color: white;
  cursor: pointer;
  transition: all 0.3s;
}

.top-controls button.active,
.top-controls button:hover {
  background: rgba(255,255,255,0.4);
}

/* 游戏状态 */
.status {
  margin-bottom: 20px;
  font-size: 1.2em;
  font-weight: bold;
}

/* 游戏棋盘 */
.game-board {
  position: relative;
  margin: 20px auto;
  box-shadow: 0 0 20px rgba(0,0,0,0.5);
}

/* 蛇身 */
.snake-segment {
  position: absolute;
  transition: all 0.1s;
}

.skin-flame .snake-segment {
  box-shadow: 0 0 10px rgba(255,0,0,0.5);
}

.skin-rainbow .snake-segment {
  animation: rainbow 5s infinite linear;
}

@keyframes rainbow {
  0% { filter: hue-rotate(0deg); }
  100% { filter: hue-rotate(360deg); }
}

/* 食物 */
.food {
  position: absolute;
  font-size: 24px;
  transition: all 0.3s;
  animation: pulse 1s infinite alternate;
}

.food-normal { color: #4CAF50; }
.food-speedUp { color: #FF4444; }
.food-speedDown { color: #0088FF; }
.food-life { color: #FF88AA; }

@keyframes pulse {
  from { transform: scale(0.9); }
  to { transform: scale(1.1); }
}

/* 控制按钮 */
.controls {
  margin-top: 20px;
}

.controls button {
  padding: 10px 20px;
  margin: 5px;
  border: none;
  border-radius: 4px;
  background: #3498db;
  color: white;
  font-size: 1em;
  cursor: pointer;
  transition: all 0.3s;
}

.controls button:hover {
  background: #2980b9;
}

/* 方向控制 */
.direction-controls {
  display: grid;
  grid-template-columns: repeat(3, 50px);
  grid-gap: 5px;
  margin: 20px auto;
  width: 160px;
}

.arrow {
  width: 50px;
  height: 50px;
  background-color: rgba(255,255,255,0.2);
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.5em;
  cursor: pointer;
  transition: all 0.2s;
}

.arrow:hover {
  background-color: rgba(255,255,255,0.4);
}

.arrow.up {
  grid-column: 2;
  grid-row: 1;
}

.arrow.left {
  grid-column: 1;
  grid-row: 2;
}

.arrow.right {
  grid-column: 3;
  grid-row: 2;
}

.arrow.down {
  grid-column: 2;
  grid-row: 3;
}

/* 排行榜 */
.leaderboard {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(0,0,0,0.8);
  padding: 20px;
  border-radius: 10px;
  z-index: 100;
  width: 300px;
  max-width: 90%;
}

.leaderboard h3 {
  margin-top: 0;
}

.leaderboard ul {
  list-style: none;
  padding: 0;
  margin: 0;
  text-align: left;
}

.leaderboard li {
  margin: 10px 0;
  padding: 5px;
  border-bottom: 1px solid rgba(255,255,255,0.2);
}

.leaderboard button {
  margin-top: 15px;
}
</style>
